package com.kede.api.stand.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.kede.api.stand.domain.SysArea;
import com.kede.api.stand.dto.RegisterUserDto;
import com.kede.api.stand.pub.ActiveLineHolde;
import com.kede.api.stand.pub.AreaInfoVo;
import com.kede.api.stand.service.SysAreaService;
import com.kede.domain.StatisDayDomain;
import com.kede.domain.UsersDomain;
import com.kede.mapper.UsersMapper;
import com.kede.pojo.ResHttp;
import com.kede.service.StatisDayService;
import com.kede.service.UsersService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 独立服务
 *
 * @author 11856
 * @date 2023/06/12
 */
@RestController
public class UsersController {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private UsersService usersService;

    @Resource
    private StatisDayService statisDayService;

    @Resource
    private SysAreaService sysAreaService;



    /**
     * 查找下一级区域 注册人数
     * @param adcodeStr
     * @return
     */
    @GetMapping("getRegisterNumByAdcode")
    public ResHttp getRegisterNumByAdcode(String adcodeStr){
        Integer adcode;
        if (StrUtil.isBlank(adcodeStr)){
            //查省份  这里adcode指的是全国
            adcode = 0;
        }else{
            try {
                adcode = Integer.valueOf(adcodeStr);
            }catch (Exception e){
                return ResHttp.failMsg("adcode 有误");
            }
        }
        LambdaQueryWrapper<SysArea> areaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (adcode.equals(0)){
            areaLambdaQueryWrapper.isNull(SysArea::getPid);
        }else{
            LambdaQueryWrapper<SysArea> OneQuery = new LambdaQueryWrapper<>();
            OneQuery.eq(SysArea::getAdcode,adcode);
            SysArea one = sysAreaService.getOne(OneQuery);
            areaLambdaQueryWrapper.eq(SysArea::getPid,one.getAdcode());
        }
        List<SysArea> sysAreas = sysAreaService.getBaseMapper().selectList(areaLambdaQueryWrapper);
        Map<Integer,Map<String,String>> areaNum = new HashMap<>();
        for (SysArea sysArea : sysAreas) {
            Map<String,String> childMap = new HashMap<>();
            LambdaQueryWrapper<UsersDomain> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UsersDomain::getAddress,sysArea.getAdcode());
            Integer integer = usersMapper.selectCount(queryWrapper);
            childMap.put("people",sysArea.getPeople());
            childMap.put("num",integer.toString());
            areaNum.put(sysArea.getAdcode(),childMap);
        }
        return ResHttp.okData(areaNum);
    }


    /**
     * 获取某时段用户注册数
     * @param userDto
     * @return
     */
    @PostMapping("getRegisterNum")
    public ResHttp staticLoginUser(@RequestBody RegisterUserDto userDto){
        LambdaQueryWrapper<UsersDomain> queryWrapper = new LambdaQueryWrapper<>();
        long end = userDto.getEnd().toEpochSecond(ZoneOffset.of("+8"));
        long start = userDto.getStart().toEpochSecond(ZoneOffset.of("+8"));
//        //小于
        queryWrapper.le(UsersDomain::getCreatetime,end);
//        //大于
        queryWrapper.ge(UsersDomain::getCreatetime,start);
        queryWrapper.eq(UsersDomain::getUserType,userDto.getUserType());
        if(ObjectUtil.isNotEmpty(userDto.getAdcode())){
            queryWrapper.eq(UsersDomain::getAddress,userDto.getAdcode());
        }
        queryWrapper.select(UsersDomain::getAddress);
        List<UsersDomain> usersDomains = usersMapper.selectList(queryWrapper);
        Map<Integer,Integer> statis = new HashMap<>();
        usersDomains.forEach(usersDomain -> {
            statis.compute(usersDomain.getAddress(),(k,v)->{
               if(v == null){
                   return 1;
               }else{
                   return ++v;
               }
            });
        });
        Map<String,Integer> response = new HashMap<>();
        statis.forEach((k,v)->{
            if(k.equals(0)){
                response.put("0",v);
            }else{
                AreaInfoVo detailByAdcode = sysAreaService.findDetailByAdcode(Integer.valueOf(k));
                if(detailByAdcode == null){
                    response.put(k.toString(),v);
                }else{
                    response.put(detailByAdcode.getCityName()+detailByAdcode.getAreaName(),v);
                }
            }

        });
        return ResHttp.okData(response);
    }

    /**
     * 获取某时段注册用户信息
     * @param userDto
     * @return
     */
    @PostMapping("getInfo")
    public ResHttp getInfo(@RequestBody RegisterUserDto userDto){
        LambdaQueryWrapper<UsersDomain> queryWrapper = new LambdaQueryWrapper<>();
        long end = userDto.getEnd().toEpochSecond(ZoneOffset.of("+8"));
        long start = userDto.getStart().toEpochSecond(ZoneOffset.of("+8"));
        queryWrapper.select(UsersDomain::getUsersName,UsersDomain::getUsersPhone);
//        //小于
        queryWrapper.le(UsersDomain::getCreatetime,end);
//        //大于
        queryWrapper.ge(UsersDomain::getCreatetime,start);
        queryWrapper.eq(UsersDomain::getUserType,userDto.getUserType());
        if(ObjectUtil.isNotEmpty(userDto.getAdcode())){
            queryWrapper.eq(UsersDomain::getAddress,userDto.getAdcode());
        }
        List<UsersDomain> list = usersMapper.selectList(queryWrapper);
        return ResHttp.okData(list);
    }


    private static final DateTimeFormatter _MonthDayFormat = DateTimeFormatter.ofPattern("MM/dd");

    /**
     * 获取用户活动数信息
     * @return
     */
    @PostMapping("getOnLine")
    public ResHttp getOnLine(@RequestBody RegisterUserDto userDto){
        LambdaQueryWrapper<StatisDayDomain> queryWrapper = new LambdaQueryWrapper<>();
        LocalDate end = userDto.getEnd().toLocalDate();
        LocalDate start = userDto.getStart().toLocalDate();
//        //小于
        queryWrapper.le(StatisDayDomain::getDate,end);
//        //大于
        queryWrapper.ge(StatisDayDomain::getDate,start);
        List<StatisDayDomain> list = statisDayService.list(queryWrapper);
        List<Map> userlist = new ArrayList();
        List<Map> adcodelist = new ArrayList();
        for (StatisDayDomain statisDayDomain : list) {
            String dayString = statisDayDomain.getDate().format(_MonthDayFormat);
            JSONObject data = JSONObject.parseObject(statisDayDomain.getData());
            JSONObject userMap = (JSONObject)data.get(ActiveLineHolde.onLineUserKey);
            JSONObject adcodeMap = (JSONObject)data.get(ActiveLineHolde.onLineAdcodeKey);
            adcodeMap.forEach((k, v) -> {
                Map item = new HashMap();
                if(k==null || k.equals("null")){
                    item.put("name","无地区信息");
                    item.put("value",v);
                }else{
                    AreaInfoVo detailByAdcode = sysAreaService.findDetailByAdcode(Integer.valueOf(k));
                    item.put("name",detailByAdcode.getCityName()+detailByAdcode.getAreaName());
                    item.put("value",v);
                }
                adcodelist.add(item);
            });
            int count = userMap.size();
            Map item = new HashMap();
            item.put("name",dayString);
            item.put("value",count);
            userlist.add(item);
        }
        //拼接上今天的
//        Map item = new HashMap();
//        item.put("name",LocalDateTime.now().format(_MonthDayFormat));
//        item.put("value",ActiveLineHolde.onLineUser.size());
//        userlist.add(item);
        Map response = new HashMap();
        response.put("userLine",userlist);
        response.put("adcodelist",adcodelist);
        return ResHttp.okData(response);
    }



    /**
     * 更新用户端app的openid
     * @param userid
     * @param openid
     * @return
     */
    @PostMapping("upUserOpenidById")
    public ResHttp upDataUserData(@RequestParam Integer userid, @RequestParam String openid){
        LambdaUpdateWrapper<UsersDomain> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(UsersDomain::getOpenid,openid);
        updateWrapper.eq(UsersDomain::getId,userid);
        boolean update = usersService.update(updateWrapper);
        if (update) {
            return ResHttp.ok();
        }else {
            return ResHttp.fail();
        }
    }

    /**
     * 更新用户端小程序的openid
     * @param userid
     * @param xcxOpenid
     * @return
     */
    @PostMapping("upUserXcxOpenidById")
    public ResHttp upUserXcxOpenidById(@RequestParam Integer userid, @RequestParam String xcxOpenid){
        LambdaUpdateWrapper<UsersDomain> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(UsersDomain::getXcxOpenid,xcxOpenid);
        updateWrapper.eq(UsersDomain::getId,userid);
        boolean update = usersService.update(updateWrapper);
        if (update) {
            return ResHttp.ok();
        }else {
            return ResHttp.fail();
        }
    }

}
